import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Popconfirm, Modal, Drawer } from 'antd';
import { PlusOutlined, DeleteOutlined, ReloadOutlined, DownloadOutlined, UploadOutlined, CloudDownloadOutlined } from '@ant-design/icons';
import type { TableConfig, FieldConfig, SearchDTO, FormDTO } from '../DynamicTable/types';
import { DynamicTable, DynamicSearchForm, DynamicForm } from '../DynamicTable';
import { PageHeader, ExportImport } from '@/components';
import { useCrudList, useMessage, useModal } from '@/hooks';
import type { FormMode } from '@/types';
import type { ExcelColumn } from '@/components/ExportImport';

interface DynamicCrudPageProps {
  // 表格配置 - 可以是静态配置或从API获取
  tableConfig?: TableConfig;
  fetchConfigApi?: () => Promise<TableConfig>;
  
  // CRUD API配置
  fetchApi: (params: any) => Promise<any>;
  createApi?: (data: any) => Promise<any>;
  updateApi?: (data: any) => Promise<any>;
  deleteApi?: (id: string) => Promise<any>;
  batchDeleteApi?: (ids: string[]) => Promise<any>;
  
  // 其他配置
  title?: string;
  initialPageSize?: number;
  // 数据转换配置
  transformData?: (data: any) => any; // 转换列表数据
  transformFormData?: (data: any, mode: 'create' | 'update') => any; // 转换表单提交数据
  transformEditData?: (data: any) => any; // 转换编辑时的初始数据（将关联对象转换为ID等）
  
  // 导入导出配置
  exportApi?: (params: any) => Promise<any>; // 导出数据接口
  importApi?: (data: any[]) => Promise<any>; // 批量导入接口
  templateApi?: () => Promise<any>; // 获取模板配置接口
  exportColumns?: ExcelColumn[]; // 导出列配置
  importValidator?: (data: any[]) => { valid: boolean; errors?: string[] }; // 导入数据验证
}

export const DynamicCrudPage: React.FC<DynamicCrudPageProps> = ({
  tableConfig: staticTableConfig,
  fetchConfigApi,
  fetchApi,
  createApi,
  updateApi,
  deleteApi,
  batchDeleteApi,
  title,
  initialPageSize = 10,
  transformData,
  transformFormData,
  transformEditData,
  exportApi,
  importApi,
  templateApi,
  exportColumns,
  importValidator,
}) => {
  const [tableConfig, setTableConfig] = useState<TableConfig | null>(staticTableConfig || null);
  const [formVisible, setFormVisible] = useState(false);
  const [formMode, setFormMode] = useState<FormMode>('create');
  const [currentRecord, setCurrentRecord] = useState<any>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailRecord, setDetailRecord] = useState<any>(null);
  const [formRef] = React.useState(() => React.createRef<any>());
  const dataLoadedRef = React.useRef(false); // 跟踪数据是否已加载
  const configLoadingRef = React.useRef(false); // 跟踪配置是否正在加载或已加载
  
  // 使用 App.useApp() hooks 获取 message 和 modal API
  const message = useMessage();
  const modal = useModal();

  // 封装 fetchApi 以处理数据格式
  const wrappedFetchApi = async (params: any) => {
    const response = await fetchApi(params);
    
    // 处理不同的响应格式
    let responseData = response;
    if (response.data) {
      responseData = response.data;
    }
    
    // 确保返回格式符合 useCrudList 的期望
    const result = {
      data: {
        success: responseData.success !== undefined ? responseData.success : true,
        data: [],
        pagination: {
          page: params.page || 1,
          pageSize: params.pageSize || initialPageSize,
          total: 0,
        },
      },
    };
    
    // 处理数据
    if (responseData.data) {
      // 如果 data 是数组，直接使用
      if (Array.isArray(responseData.data)) {
        result.data.data = responseData.data;
        result.data.pagination.total = responseData.total || responseData.data.length;
      }
      // 如果 data 是对象，可能包含 list/data 字段
      else if (typeof responseData.data === 'object') {
        result.data.data = responseData.data.list || responseData.data.data || [];
        result.data.pagination.total = responseData.data.total || responseData.total || 0;
        result.data.pagination.page = responseData.data.page || params.page || 1;
        result.data.pagination.pageSize = responseData.data.pageSize || params.pageSize || initialPageSize;
      }
    }
    
    // 应用自定义数据转换
    if (transformData) {
      result.data.data = transformData(result.data.data);
    }
    
    return result;
  };
  
  // 加载表格配置 - 必须在数据加载之前完成
  useEffect(() => {
    // 如果已经有配置了，不再加载
    if (tableConfig) return;
    // 如果正在加载或已加载，不再重复加载
    if (configLoadingRef.current) return;
    
    if (fetchConfigApi && !staticTableConfig) {
      // 标记为正在加载
      configLoadingRef.current = true;
      // 使用 fetchConfigApi 加载配置
      fetchConfigApi()
        .then(config => {
          console.log('Table config loaded:', config);
          console.log('Fields count:', config?.fields?.length);
          if (!config || !config.fields || !Array.isArray(config.fields) || config.fields.length === 0) {
            console.warn('Table config is invalid or has no fields:', config);
            message.warning('表格配置无效或没有字段配置');
          }
          setTableConfig(config);
        })
        .catch(error => {
          message.error('加载表格配置失败');
          console.error('Failed to load table config:', error);
          configLoadingRef.current = false; // 失败后允许重试
        });
    } else if (staticTableConfig) {
      // 如果有静态配置，直接设置
      configLoadingRef.current = true;
      setTableConfig(staticTableConfig);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetchConfigApi, staticTableConfig, tableConfig]); // 依赖 fetchConfigApi、staticTableConfig 和 tableConfig

  // 使用CRUD Hook
  // 如果有静态配置，立即自动加载；如果使用 fetchConfigApi，等配置加载完成后再加载
  const {
    data,
    loading,
    pagination,
    searchParams,
    handleSearch,
    handleReset,
    handlePageChange,
    refresh,
  } = useCrudList({
    fetchApi: wrappedFetchApi,
    initialPageSize,
    autoLoad: !!staticTableConfig, // 只有静态配置时才自动加载
  });

  // 配置加载完成后，自动加载数据（仅当使用 fetchConfigApi 时）
  useEffect(() => {
    if (dataLoadedRef.current) return; // 防止重复加载
    
    if (tableConfig && !staticTableConfig && fetchConfigApi) {
      // 只有在通过 fetchConfigApi 加载配置时才自动加载数据
      dataLoadedRef.current = true;
      refresh();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tableConfig]); // 只依赖 tableConfig，当配置加载完成时触发

  // 处理新增
  const handleCreate = () => {
    setFormMode('create');
    setCurrentRecord(null);
    setFormVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: any) => {
    setFormMode('edit');
    // 如果提供了 transformEditData，先转换数据
    const editData = transformEditData ? transformEditData(record) : record;
    setCurrentRecord(editData);
    setFormVisible(true);
  };

  // 处理删除
  const handleDelete = async (id: string) => {
    if (!deleteApi) {
      message.warning('未配置删除接口');
      return;
    }

    try {
      const response = await deleteApi(id);
      const result = response.data || response;
      if (result.success) {
        message.success(result.message || '删除成功');
        refresh();
      }
    } catch (error: any) {
      console.error('Delete failed:', error);
      message.error(error.response?.data?.message || error.message || '删除失败');
    }
  };

  // 处理批量删除
  const handleBatchDelete = async () => {
    if (!batchDeleteApi) {
      message.warning('未配置批量删除接口');
      return;
    }

    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的数据');
      return;
    }

    try {
      const response = await batchDeleteApi(selectedRowKeys as string[]);
      const result = response.data || response;
      if (result.success) {
        message.success(result.message || `成功删除 ${selectedRowKeys.length} 条数据`);
        setSelectedRowKeys([]);
        refresh();
      }
    } catch (error: any) {
      console.error('Batch delete failed:', error);
      message.error(error.response?.data?.message || error.message || '批量删除失败');
    }
  };

  // 处理表单提交
  const handleFormSubmit = async (values: FormDTO) => {
    try {
      // 清理不需要的字段
      const submitData = { ...values };
      // 删除通常不需要提交的字段
      const fieldsToRemove = [
        'createdAt', 'updatedAt', 'deletedAt',
        'created_at', 'updated_at', 'deleted_at',
        'lastLoginAt', 'lastLoginIp',
        'last_login_at', 'last_login_ip',
      ];
      
      // 删除关联对象字段（保留 ID 字段）
      Object.keys(submitData).forEach(key => {
        if (fieldsToRemove.includes(key)) {
          delete submitData[key];
        }
        // 如果是对象且不是数组，可能是关联对象
        if (submitData[key] && typeof submitData[key] === 'object' && !Array.isArray(submitData[key])) {
          // 检查是否有对应的 ID 字段
          const idKey = key.replace(/s?$/, 'Id');
          if (!submitData[idKey]) {
            delete submitData[key];
          }
        }
      });
      
      // 应用自定义表单数据转换
      // 将 FormMode 的 'edit' 转换为 transformFormData 期望的 'update'
      const transformMode = formMode === 'edit' ? 'update' : formMode;
      const finalData = transformFormData 
        ? transformFormData(submitData, transformMode as 'create' | 'update') 
        : submitData;
      
      if (formMode === 'create') {
        if (!createApi) {
          message.warning('未配置创建接口');
          return;
        }
        const response = await createApi(finalData);
        const result = response.data || response;
        if (result.success) {
          message.success(result.message || '创建成功');
        }
      } else {
        if (!updateApi) {
          message.warning('未配置更新接口');
          return;
        }
        const response = await updateApi({ ...finalData, id: currentRecord?.id });
        const result = response.data || response;
        if (result.success) {
          message.success(result.message || '更新成功');
        }
      }

      setFormVisible(false);
      refresh();
    } catch (error: any) {
      console.error('Submit failed:', error);
      message.error(error.response?.data?.message || error.message || '操作失败');
    }
  };

  // 处理搜索
  const handleSearchSubmit = (values: SearchDTO) => {
    handleSearch(values);
  };

  // 处理导出
  const handleExport = async () => {
    if (!exportApi) {
      message.warning('未配置导出接口');
      return [];
    }

    try {
      // 获取当前搜索条件的所有数据
      const response = await exportApi(searchParams);
      const result = response.data || response;
      
      if (result.success) {
        return result.data || [];
      }
      
      message.error('获取导出数据失败');
      return [];
    } catch (error: any) {
      console.error('Export failed:', error);
      message.error(error.response?.data?.message || error.message || '导出失败');
      return [];
    }
  };

  // 处理导入
  const handleImport = async (data: any[]) => {
    if (!importApi) {
      message.warning('未配置导入接口');
      return;
    }

    try {
      const response = await importApi(data);
      const result = response.data || response;
      
      if (result.success) {
        const { success = [], failed = [] } = result.data || {};
        
        if (failed.length > 0) {
          modal.warning({
            title: '部分数据导入失败',
            content: (
              <div>
                <p>成功：{success.length} 条</p>
                <p>失败：{failed.length} 条</p>
                <div style={{ maxHeight: 200, overflow: 'auto' }}>
                  {failed.map((item: any, index: number) => (
                    <div key={index} style={{ marginBottom: 4 }}>
                      • {item.email || item.name || `第${index + 1}条`}: {item.error}
                    </div>
                  ))}
                </div>
              </div>
            ),
          });
        } else {
          message.success(`成功导入 ${success.length} 条数据`);
        }
        
        refresh();
      } else {
        message.error(result.message || '导入失败');
      }
    } catch (error: any) {
      console.error('Import failed:', error);
      message.error(error.response?.data?.message || error.message || '导入失败');
    }
  };

  // 获取模板配置
  const [templateConfig, setTemplateConfig] = useState<{ columns: ExcelColumn[]; sampleData?: any[] } | null>(null);
  
  useEffect(() => {
    if (templateApi) {
      templateApi().then(response => {
        const result = response.data || response;
        if (result.success && result.data) {
          setTemplateConfig(result.data);
        }
      }).catch(error => {
        // 静默失败，不显示错误提示（因为模板配置是可选的）
        console.error('Failed to load template config:', error);
      });
    }
  }, [templateApi]);

  if (!tableConfig) {
    return <Card loading={true} />;
  }

  return (
    <div>
      <PageHeader
        title={title || tableConfig.name}
        extra={
          <Space>
            {/* 导入导出按钮 */}
            {(tableConfig.actions?.export || tableConfig.actions?.import) && (
              <ExportImport
                onExport={tableConfig.actions?.export && exportApi ? handleExport : undefined}
                onImport={tableConfig.actions?.import && importApi ? handleImport : undefined}
                exportColumns={exportColumns}
                exportFilename={tableConfig.name || 'export'}
                showExportButton={!!tableConfig.actions?.export && !!exportApi}
                showImportButton={!!tableConfig.actions?.import && !!importApi}
                showTemplateButton={!!tableConfig.actions?.import && !!templateConfig}
                templateColumns={templateConfig?.columns}
                templateSampleData={templateConfig?.sampleData}
                templateFilename={tableConfig.name || 'import'}
                validateImportData={importValidator}
                buttonSize="middle"
              />
            )}
            
            {/* 批量删除按钮 */}
            {tableConfig.actions?.batchDelete && batchDeleteApi && (
              <Popconfirm
                title={`确定要删除选中的 ${selectedRowKeys.length} 条数据吗？`}
                onConfirm={handleBatchDelete}
                disabled={selectedRowKeys.length === 0}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  danger
                  disabled={selectedRowKeys.length === 0}
                  icon={<DeleteOutlined />}
                >
                  批量删除 ({selectedRowKeys.length})
                </Button>
              </Popconfirm>
            )}

            {/* 刷新按钮 */}
            <Button
              icon={<ReloadOutlined />}
              onClick={refresh}
              loading={loading}
            >
              刷新
            </Button>

            {/* 新增按钮 */}
            {tableConfig.actions?.create && createApi && (
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleCreate}
              >
                新增
              </Button>
            )}
          </Space>
        }
      />

      {/* 搜索表单 */}
      <DynamicSearchForm
        fields={tableConfig.fields}
        onSearch={handleSearchSubmit}
        onReset={handleReset}
        loading={loading}
      />

      {/* 数据表格 */}
      <Card>
        <DynamicTable
          config={tableConfig}
          dataSource={data}
          loading={loading}
          onCreate={tableConfig.actions?.create && createApi ? handleCreate : undefined}
          onEdit={tableConfig.actions?.update && updateApi ? handleEdit : undefined}
          onDelete={tableConfig.actions?.delete && deleteApi ? handleDelete : undefined}
          onBatchDelete={tableConfig.actions?.batchDelete && batchDeleteApi ? handleBatchDelete : undefined}
          onSearch={handleSearchSubmit}
          showToolbar={false}
          selectedRowKeys={selectedRowKeys}
          onSelectedRowKeysChange={setSelectedRowKeys}
        />
      </Card>

      {/* 表单弹窗 */}
      <Modal
        title={formMode === 'create' ? '新增' : '编辑'}
        open={formVisible}
        onCancel={() => setFormVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setFormVisible(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={loading}
            onClick={() => {
              // 通过ref获取表单实例并提交
              if (formRef.current) {
                formRef.current.submit();
              }
            }}
          >
            确定
          </Button>,
        ]}
        width={800}
        destroyOnHidden
      >
        <DynamicForm
          fields={tableConfig.fields}
          initialValues={currentRecord}
          mode={formMode}
          onFinish={handleFormSubmit}
          form={formRef.current}
        />
      </Modal>

      {/* 详情抽屉 */}
      <Drawer
        title="详情"
        placement="right"
        width={600}
        onClose={() => setDetailVisible(false)}
        open={detailVisible}
      >
        {detailRecord && (
          <DynamicForm
            fields={tableConfig.fields}
            initialValues={detailRecord}
            mode="view"
          />
        )}
      </Drawer>
    </div>
  );
};

export default DynamicCrudPage;
